# coding=utf-8
import ConfigParser
import os
import sys
import warnings

# warnings.simplefilter('error')
os.environ["DJANGO_SETTINGS_MODULE"] = "xls_demo.settings"


def get_base_dir(current_file):
    _base = os.path.dirname(current_file)
    if _base == current_file:
        return None

    if os.path.isdir(_base):
        return _base

    else:
        return get_base_dir(_base)

try:
    xls_demo_base_path = get_base_dir(__file__)
except:
    xls_demo_base_path = get_base_dir(sys.argv[0])

xls_demo_root_path = os.path.join(xls_demo_base_path, 'xls_demo')
filenames = ['PYT', 'CHE', 'JIE', 'MEM', 'MYS', 'NTP', 'PYP', 'DJA', 'UPY', 'BAN']
library_files = ','.join([os.path.join(xls_demo_root_path, i+'.dat') for i in filenames])
resource_file = os.path.join(xls_demo_root_path, 'resources.dll')
ini_file = os.path.join(xls_demo_base_path, 'settings.ini')

os.environ['XLS_DEMO_BASE_PATH'] = xls_demo_base_path
os.environ['XLS_DEMO_ROOT_PATH'] = xls_demo_root_path
os.environ['XLS_DEMO_SETTINGS_FILE'] = ini_file
os.environ['XLS_DEMO_RESOURCE_FILE'] = resource_file
os.environ['XLS_DEMO_LIBRARY_FILES'] = library_files
os.environ['XLS_DEMO_LIBRARY_PASSWORD'] = 'xls_demo_library_password_ab3c3s'
os.environ['XLS_DEMO_RESOURCE_PASSWORD'] = 'xls_demo_resource_password_5e98sw'


SERVER_SETTINGS = {
    'server': {
        'ip': '0.0.0.0',
        'port': 8000,
        'thread': 30,
        'debug': 0,
    },
    'db': {
        'ip': '127.0.0.1',
        'port': 3306,
        'user': 'root',
        'password': '',
        'name': 'xls_demo',
    }
}
CONFIG = {}

parser = ConfigParser.ConfigParser()

try:
    parser.readfp(open(ini_file))
    for sec in parser.sections():
        CONFIG[sec] = {}
        items = parser.items(sec)
        for item in items:
            CONFIG[sec][item[0]] = item[1]

except:
    pass

SERVER_SETTINGS.update(CONFIG)


os.environ.setdefault('XLS_DEMO_HTTP_HOST', SERVER_SETTINGS['server']['ip'])
os.environ.setdefault('XLS_DEMO_HTTP_PORT', str(SERVER_SETTINGS['server']['port']))
os.environ.setdefault('XLS_DEMO_HTTP_THREAD', str(SERVER_SETTINGS['server']['thread']))
os.environ.setdefault('XLS_DEMO_HTTP_DEBUG', str(SERVER_SETTINGS['server']['debug']))

os.environ.setdefault('XLS_DEMO_DB_HOST', SERVER_SETTINGS['db']['ip'])
os.environ.setdefault('XLS_DEMO_DB_PORT', str(SERVER_SETTINGS['db']['port']))
os.environ.setdefault('XLS_DEMO_DB_USER', SERVER_SETTINGS['db']['user'])
os.environ.setdefault('XLS_DEMO_DB_PASSWORD', SERVER_SETTINGS['db']['password'])
os.environ.setdefault('XLS_DEMO_DB_NAME', SERVER_SETTINGS['db']['name'])
